package cxt.com.recyclerview.demo3;

import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;

import java.util.Collections;
import java.util.List;

import cxt.com.recyclerview.demo1.DataModel;

/**
 * 作者：chengxiangtong on 2017/1/10 10:33
 * 邮箱：528440900@qq.com
 */

public class SimpleItemTouchCallback extends ItemTouchHelper.Callback {

    private NormalAdapter mNormalAdapter;
    private List<DataModel> mDataModel;

    public SimpleItemTouchCallback(NormalAdapter mNormalAdapter, List<DataModel> mDataModel) {
        this.mNormalAdapter = mNormalAdapter;
        this.mDataModel = mDataModel;
    }

    /**
     * 设置支持的拖拽、滑动的方向
     *
     * @param recyclerView
     * @param viewHolder
     * @return
     */
    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        int swipeFlag = ItemTouchHelper.START | ItemTouchHelper.END;
        return makeMovementFlags(dragFlag, swipeFlag);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        int from = viewHolder.getAdapterPosition();
        int to = target.getAdapterPosition();
        Collections.swap(mDataModel, from, to);
        mNormalAdapter.notifyItemMoved(from, to);
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        int pos = viewHolder.getAdapterPosition();
        mDataModel.remove(pos);
        mNormalAdapter.notifyItemRemoved(pos);
    }

    /**
     * 状态改变时回调
     *
     * @param viewHolder
     * @param actionState
     */
    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        super.onSelectedChanged(viewHolder, actionState);
        Log.i("CallBack", actionState + "");
        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
            NormalAdapter.VH holder = (NormalAdapter.VH) viewHolder;
            holder.imageView.setBackgroundColor(0xffbcbcbc);
        }
    }

    /**
     * 拖拽或滑动完成之后调用，用来清除一些状态】
     */
    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
        NormalAdapter.VH holder = (NormalAdapter.VH) viewHolder;
        holder.imageView.setBackgroundColor(0xffeeeeee);
    }
}
